var bt = baidu.template;
var currentTab = $('#nav').find('.cur').data('goto');
var isFirstLoad = true;

function openInWebView(e) {
    e.preventDefault();
    var _url = $(this).attr('data-url');
    _hmt.push(['_trackEvent', 'product_list', 'click', _url]);
    btAppSchema.jumpToWebView(_url);
}
function Products (option) {
    this.productName = option.productName;
    this.loadUrl = option.loadUrl;
    this.loadPage = 0;
    this.loadTimes = 0;
    this._init();
}
Products.prototype = {
    _init: function () {
        var productsContent = '';
    },
    getProducts: function (page) {
        var _self = this;
        if ( _self.loadPage === null ) {
            $('#departnow-more').addClass('hide');
            return false;
        }
        page = page || 0;
        if ( _self.productName == currentTab || _self.loadTimes === 0 ) {
            $.get(_self.loadUrl + page, function(data) {
                _self.productsContent = bt('product_template', {list: data.products,type: _self.productName});
                $(_self.productsContent).appendTo('#'+ _self.productName + '-list');
                _self.handleDOM();
                if ( data.has_more ) {
                    $(document).on('scroll', _self.loadProducts());
                }else{
                    $(document).off('scroll',_self.loadProducts());
                    $('#'+ _self.productName + '-more').addClass('hide');
                }
                _self.loadPage = data.next_page;
                if( isFirstLoad ){
                    //第一次成功加载后展现头部tab
                    isFirstLoad = false;
                    $('header').show();
                }
                if ( _self.loadTimes === 0 ) {
                    _self.loadProducts();
                }
                _self.loadTimes++;
            });
        }
    },
    loadProducts: function () {
        var _self = this;
        this.loadHandeler = this.loadHandeler || function(e){
            var reachBottom = document.body.scrollTop + window.innerHeight >= $(document).height() - 200;
            if ( reachBottom && _self.productName == currentTab ) {
                $(document).off('scroll',_self.loadProducts());
                _self.getProducts(_self.loadPage);
            }
        };
        return this.loadHandeler;
    },
    setCountDown: function ( time, id ) {
        var _self = this;
        var _obj = {
            product: id,
            sec: document.getElementById(_self.productName+"-sec-"+id),
            mini: document.getElementById(_self.productName+"-mini-"+id),
            hour: document.getElementById(_self.productName+"-hour-"+id),
            day: document.getElementById(_self.productName+"-day-"+id)
        };
        _self.fnTimeCountDown(time, _obj);
    },
    handleDOM: function() {
        var _self = this;
        var _li = $('#'+ _self.productName + '-list').find('li');
        $.each(_li, function(i, val) {
            if ( $(this).data('time') ) {
                var _id = $(this).data('id'),
                    _time = $(this).data('time') * 1000;
                _self.setCountDown( _time, _id );
                $(this).find('.countdown p').removeClass('hide');
            }else{
                $(this).find('.countdown p').hide();
            }
        });
    },
    fnTimeCountDown: function(d, o) {
        var f = {
            zero: function(n) {
                var n = parseInt(n, 10);
                if (n > 0) {
                    if (n <= 9) {
                        n = "0" + n;
                    }
                    return String(n);
                } else {
                    return "00";
                }
            },
            dv: function() {
                d = d || Date.UTC(2050, 0, 1);
                var future = new Date(d),
                    now = new Date();
                //现在将来秒差值
                var dur = Math.round((future.getTime() - now.getTime()) / 1000) + future.getTimezoneOffset() * 60,
                    pms = {
                        sec: "00",
                        mini: "00",
                        hour: "00",
                        day: "00",
                        month: "00",
                        year: "0"
                    };
                if (dur > 0) {
                    pms.sec = f.zero(dur % 60);
                    pms.mini = Math.floor((dur / 60)) > 0 ? f.zero(Math.floor((dur / 60)) % 60) : "00";
                    pms.hour = Math.floor((dur / 3600)) > 0 ? f.zero(Math.floor((dur / 3600)) % 24) : "00";
                    pms.day = Math.floor((dur / 86400)) > 0 ? f.zero(Math.floor((dur / 86400))) : "00";
                }else if(dur < 0 && $(o.sec).parents('.countdown').hasClass('countdown-seckill') ){
                    $(o.sec).parents('p').html('抢购进行中');
                }
                return pms;
            },
            ui: function() {
                if (o.sec) {
                    o.sec.innerHTML = f.dv().sec;
                }
                if (o.mini) {
                    o.mini.innerHTML = f.dv().mini;
                }
                if (o.hour) {
                    o.hour.innerHTML = f.dv().hour;
                }
                if (o.day) {
                    o.day.innerHTML = f.dv().day;
                }
                setTimeout(f.ui, 1000);
            }
        };
        f.ui();
    }
};
var departUrl = BT.context('preview') == '1' ? '/coolproduct/departnow/?preview=1&page=':'/coolproduct/departnow/?page=';
var placeUrl = BT.context('preview') == '1' ? '/coolproduct/place/?preview=1&page=':'/coolproduct/place/?page=';
var peopleUrl = BT.context('preview') == '1' ? '/coolproduct/people_list/?preview=1&page=':'/coolproduct/people_list/?page=';
var DepartnowProducts = new Products({
    productName: 'departnow',
    loadUrl: departUrl,
    loadPage: 1
});
var PlaceProducts = new Products({
    productName: 'place',
    loadUrl: placeUrl,
    loadPage: 1
});
var PeopleProducts = new Products({
    productName: 'people',
    loadUrl: peopleUrl,
    loadPage: 1
});
var hashType = {
    "#departnow-hash" : "departnow",
    "#place-hash" : "place",
    "#people-hash" : "people"
};
function showTab(hash){
    if(!hash){
        hash = '#departnow';
    }
    $('#nav a[data-goto='+hashType[hash]+']').addClass('cur').siblings().removeClass('cur');
    $('#' + hashType[hash]).removeClass('hide').siblings('section').addClass('hide');
}
$(function(){
    DepartnowProducts.getProducts();
    PlaceProducts.getProducts();
    PeopleProducts.getProducts();

    if ('onhashchange' in window) {
        window.addEventListener("hashchange",function(event){
            event.preventDefault();
            var hash = window.location.hash;
            showTab(hash);
        });
    }

    $("#nav a").on("click", function(event) {
        if ($(this).hasClass('cur')) {
            event.preventDefault();
        }
        document.body.scrollTop = 0;
        var trackName = 'product_list_nav_'+$(this).data('goto');
        _hmt.push(['_trackEvent', 'product_list', 'click', trackName]);
    });
    showTab(location.hash);

    $('ul').on('click', 'li', openInWebView);
    $('#departnow-more').on('click', function(e) {
        e.preventDefault();
        if ( !$('#departnow-more').hasClass('hide') ) {
            loadDepartnowProducts(DepartnowProductsPage);
        }
    });
    $('#place-more').on('click', function(e) {
        e.preventDefault();
    });
    $('#people-more').on('click', function(e) {
        e.preventDefault();
    });
});